﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

//This Class specific System namespaces
using System.Data;
using System.Data.Common;

//This Class Specific IvyFramework namespaces
using Ivy.Common.Framework.Base;
using Ivy.Common.Framework.DataAccess;

using Ivy.ContentManagement.Entity;

namespace Ivy.ContentManagement.DataAccess
{
    public class ContentSummaryDao
    {
        #region  Variable & constant
        // All constants and local variable should be declared here
        // TRY NOT TO CREATE PUBLIC VARIABLES INSTEAD USE PROPERTIES FOR THAT PURPOSE.
        // Variable naming convention :- 
        // The naming should be self explanatory, make it long to explain the purpose 
        // and use PascalCase to seperate words as shown in the example below.
        // DO NOT USE ANY ABBRIVIATION use full word (like "Customer" instead of "Cust"
        // Naming convention for all local variable should start with underscore "_"
        // Naming convention for all local constant should start with "_The"
        // Example :    string _CustomerCode = string.Empty;
        // Example :    const string _TheDefaultSmtpServer = "DefaultSmtpServer";
        // ==================== START YOUR CODE FROM NEXT LINE ========================

        #endregion  Variable & constant

        #region Constructor & Destructor
        // Cut and Copy the default constructor for the class inside this region.
        // Generally not required in UI layer.
        // Example:
        // public SampleClassTemplate()
        // {

        // }
        // ==================== START YOUR CODE FROM NEXT LINE ========================

        #endregion Constructor & Destructor

        #region Properties
        // Any value/variable that needs to be exposed outside the class we need to create a property.
        // Avoid creating public variables rather create public properties.
        // UI layer may have public custom properties. these are very handy for User Controls.
        // Property naming convention :- Properties will be exposed outside the class, 
        // the naming should be self explanatory, make it long to explain the purpose 
        // and use PascalCase to seperate words as shown in the example below.
        // DO NOT USE ANY ABBRIVIATION use full word (like "Customer" instead of "Cust"
        // All properties should have a corresponding local variable 
        // and the property name and local variable name should match.
        // Example :
        // public string CustomerCode
        // {
        //     get
        //     {
        //         return _CustomerCode;
        //     }
        //     set
        //     {
        //         _CustomerCode = value;
        //     }
        // }
        // ==================== START YOUR CODE FROM NEXT LINE ========================

        #endregion Properties

        #region Events
        // Generally UI layer will have public events.
        // Cut and Copy the default generated events for the class inside this region.
        // ==================== START YOUR CODE FROM NEXT LINE ========================

        #endregion Events

        #region Public Methods

        // Any method that needs to be exposed outside the class will be created inside this region.
        // Public Method naming convention :- Public Method will be exposed outside the class, 
        // The input and output parameters are also going to be exposed outside the class
        // the naming should be self explanatory, make it long to explain the purpose 
        // and use PascalCase to seperate words as shown in the example below.
        // DO NOT USE ANY ABBRIVIATION use full word (like "Customer" instead of "Cust"
        // Example :
        // public bool RegisterNewCustomer(Customer Customer)
        // {
        //     bool IsCustomerDataSaved = false;
        //     //TO DO logic to save data
        //     IsCustomerDataSaved = InsertCustomerDataUsingDao(Customer);
        //     return IsCustomerDataSaved;
        // }
        // ==================== START YOUR CODE FROM NEXT LINE ========================

        /// <summary>
        /// IDaoInterface GETALL method with "IsNotDeletedOnly" & "OrganizationID" parameter is used to Retrive a Collection of existing records from Database and converts data to an instance of the EntityObject LIST
        /// The "IsNotDeletedOnly" input flag is used when the Table may hold record which has been "SOFT DELETED" and
        /// The "OrganizationID" input parameter is used when the Table is holding Records for more than one Organization (SaaS Model) 
        /// THIS METHOD MAY NOT BE IMPLEMENTED. by using "throw new NotImplementedException();"
        /// </summary>
        /// <param name="IsNotDeletedOnly"></param>
        /// <param name="OrganizationID"></param>
        /// <returns></returns>
        public List<ContentSummary> GetAll(int ContentTypeKey, bool IsNotDeleted, int OrganizationID)
        {
            //THIS METHOD MAY NOT BE IMPLEMENTED. by REMOVING the below code and REPLACING it with "throw new NotImplementedException();"

            //throw new NotImplementedException();

            List<ContentSummary> _ContentSummaryObjectList = new List<ContentSummary>();

            DbConnection DbConn = DataAccessProviderUtility.CreateConnectionWithConnectionString();
            DbCommand CmdObj = DataAccessProviderUtility.CreateCommand();
            CmdObj.CommandText = "Ivy_ContentManagement_ContentSummary_GetAllByTypeAndOrganization";
            CmdObj.CommandType = CommandType.StoredProcedure;

            //INPUT PARAMETERS FOR STORED PROCEDURE
            //The STORED PROC should have the below parameters
            if (ContentTypeKey != null)
            {
                DataAccessProviderUtility.AddParameter(CmdObj, "@ContentTypeKey", ParameterDirection.Input, DbType.Int32, (ContentTypeKey));
            }

            DataAccessProviderUtility.AddParameter(CmdObj, "@Sys_IsDeleted", ParameterDirection.Input, DbType.Boolean, (IsNotDeleted));
            if (OrganizationID != null)
            {
                DataAccessProviderUtility.AddParameter(CmdObj, "@Sys_OrganizationID", ParameterDirection.Input, DbType.Int32, (OrganizationID));
            }
            CmdObj.Connection = DbConn;
            DbConn.Open();
            CmdObj.Prepare();

            DbDataReader _DataReader = CmdObj.ExecuteReader();
            if (_DataReader.HasRows)
            {
                while (_DataReader.Read())
                {
                    ContentSummary _ContentSummaryTempObject = new ContentSummary(); //IMPORTANT NOTE:- Create instance only when required.
                    //Always use a private TRANSALATE method transfer data from DataReader fields to an instance of EntityObject
                    this.TranslateContentSummaryFieldsFromReaderToEntity(_ContentSummaryTempObject, _DataReader);
                    _ContentSummaryObjectList.Add(_ContentSummaryTempObject);
                }
            }
            CmdObj.Dispose();
            DbConn.Close();

            return _ContentSummaryObjectList;
        }
        #endregion Public Methods

        #region Private Methods
        // All local class level methods will be inside this region. Mostly these are helper methods.
        // Private Method naming convention :- The naming should be self explanatory, 
        // make it long to explain the purpose and use PascalCase to seperate words as shown in the example below.
        // DO NOT USE ANY ABBRIVIATION use full word (like "Customer" instead of "Cust"
        // Input parameter will have a "p" as prefix. 
        // This will help the parameter variable that the value is originated outside this private method.
        // Example :
        // public bool InsertCustomerDataUsingDao(Customer pCustomer)
        // {
        //     bool IsCustomerDataInsertedSuccessfully = false;
        //     //TO DO logic to save data
        //     //....
        //     //....
        //     return IsCustomerDataInsertedSuccessfully;
        // }
        // ==================== START YOUR CODE FROM NEXT LINE ========================
        //private void TranslateContentSummaryFromEntityToDatabaseParameters(DbCommand pDbCommand, ContentSummary pEntityObject)
        //{
        //    //REMOVE THE BELOW SAMPLE CODE AND REPLACE WITH ACTUAL CODE
        //    //DataAccessProviderUtility.AddParameter(pDbCommand, "@Parameter_1", ParameterDirection.Input, DbType.String, pEntityObject.-----);

        //    //if (pEntityObject.---Datetime != null)
        //    //{
        //    //    DataAccessProviderUtility.AddParameter(pDbCommand, "@Parameter_2DateTime", ParameterDirection.Input, DbType.DateTime, pEntityObject.---Datetime);
        //    //}
        //    //else
        //    //{
        //    //    DataAccessProviderUtility.AddParameter(pDbCommand, "@Parameter_2DateTime", ParameterDirection.Input, DbType.DateTime, DBNull.Value);
        //    //}
        //    // TODO
        //    // TODO
        //    // TODO

        //    //Always use this Base Class method to populate "Sys_xxxxxx" parameters for the Entity
        //    if (pEntityObject.EntityState == EntityState.New) //Check if this is insert action
        //    {
        //        DatabaseCommon.InsertStoredProcForParameterDatEntityBase(pDbCommand, pEntityObject);
        //    }
        //    if (pEntityObject.EntityState == EntityState.Changed) //Check if this update action
        //    {
        //        DataAccessProviderUtility.AddParameter(pDbCommand, "@ConcurrencyTimeStamp", ParameterDirection.Input, DbType.DateTime, pEntityObject.ConcurrencyTimeStamp);
        //        DatabaseCommon.UpdateStoredProcForParameterDatEntityBase(pDbCommand, pEntityObject);
        //    }
        //}
        private void TranslateContentSummaryFieldsFromReaderToEntity(ContentSummary pContentSummaryObject, DbDataReader pDbDataReader)
        {
            pContentSummaryObject.ContentKey = Convert.ToInt32(pDbDataReader["ContentKey"]);
            pContentSummaryObject.ContentCode = Convert.ToString(pDbDataReader["ContentCode"]);
            pContentSummaryObject.ContentName = Convert.ToString(pDbDataReader["ContentName"]);
            pContentSummaryObject.ContentTypeKey = Convert.ToInt32(pDbDataReader["ContentTypeKey"]);
            pContentSummaryObject.ContentTypeCode = Convert.ToString(pDbDataReader["ContentTypeCode"]);
            pContentSummaryObject.ContentTypeName = Convert.ToString(pDbDataReader["ContentTypeName"]);
            pContentSummaryObject.ContentStatus = Convert.ToInt32(pDbDataReader["ContentStatus"]);

            if (pDbDataReader["ContentPublicationStartDate"] != DBNull.Value)
            {
                pContentSummaryObject.ContentPublicationStartDate = Convert.ToDateTime(pDbDataReader["ContentPublicationStartDate"]);
            }

            pContentSummaryObject.ContentHtmlData = Convert.ToString(pDbDataReader["ContentHtmlData"]);
            if (pDbDataReader["ContentMetaTagKeyword"] != DBNull.Value)
            {
                pContentSummaryObject.ContentMetaTagKeyword = Convert.ToString(pDbDataReader["ContentMetaTagKeyword"]);
                                                                                              
            }
            
            if (pDbDataReader["ContentMetaTagDescription"] != DBNull.Value)
            {
                pContentSummaryObject.ContentMetaTagDescription = Convert.ToString(pDbDataReader["ContentMetaTagDescription"]);
            }
            if (pDbDataReader["ContentTotalLikes"] != DBNull.Value)
            {
                pContentSummaryObject.ContentTotalLikes = Convert.ToInt32(pDbDataReader["ContentTotalLikes"]);
            }
            if (pDbDataReader["ContentTotalViews"] != DBNull.Value)
            {
                pContentSummaryObject.ContentTotalViews = Convert.ToInt32(pDbDataReader["ContentTotalViews"]);
            }
            pContentSummaryObject.Sys_DateOfCreation = Convert.ToDateTime(pDbDataReader["Sys_DateOfCreation"]);
            pContentSummaryObject.Sys_CreatedById = Convert.ToString(pDbDataReader["Sys_CreatedById"]);
            pContentSummaryObject.PersonFirstName = Convert.ToString(pDbDataReader["PersonFirstName"]);
            if (pDbDataReader["PersonLastName"] != DBNull.Value)
            {
                pContentSummaryObject.PersonLastName = Convert.ToString(pDbDataReader["PersonLastName"]);
            }
            if (pDbDataReader["PersonProfileImageData"] != DBNull.Value)
            {
                pContentSummaryObject.PersonProfileImageData = (Byte[])(pDbDataReader["PersonProfileImageData"]);
            }
            if (pDbDataReader["PersonImageType"] != DBNull.Value)
            {
                pContentSummaryObject.PersonImageType = Convert.ToString(pDbDataReader["PersonImageType"]);
            }
            if (pDbDataReader["PersonImageFileName"] != DBNull.Value)
            {
                pContentSummaryObject.PersonImageFileName = Convert.ToString(pDbDataReader["PersonImageFileName"]);
            }
            if (pDbDataReader["ContentImageKey"] != DBNull.Value)
            {
                pContentSummaryObject.ContentImageKey = Convert.ToInt32(pDbDataReader["ContentImageKey"]);
            }
            if (pDbDataReader["ContentImageData"] != DBNull.Value)
            {
                pContentSummaryObject.ContentImageData = (Byte[])(pDbDataReader["ContentImageData"]);
            }
            if (pDbDataReader["ContentImageType"] != DBNull.Value)
            {
                pContentSummaryObject.ContentImageType = Convert.ToString(pDbDataReader["ContentImageType"]);
            }
            if (pDbDataReader["ContentImageFileName"] != DBNull.Value)
            {
                pContentSummaryObject.ContentImageFileName = Convert.ToString(pDbDataReader["ContentImageFileName"]);
            }
            if (pDbDataReader["AverageRating"] != DBNull.Value)
            {
                pContentSummaryObject.AverageRating = Convert.ToInt32(pDbDataReader["AverageRating"]);
            }
            if (pDbDataReader["TotalReviews"] != DBNull.Value)
            {
                pContentSummaryObject.TotalReviews = Convert.ToInt32(pDbDataReader["TotalReviews"]);
            }
            pContentSummaryObject.Sys_DeleteType = Convert.ToInt32(pDbDataReader["Sys_DeleteType"]);
            pContentSummaryObject.Sys_IsDeleted = Convert.ToBoolean(pDbDataReader["Sys_IsDeleted"]);
            pContentSummaryObject.Sys_OrganizationId = Convert.ToInt32(pDbDataReader["Sys_OrganizationId"]);

            //Always use this Base Class method to populate Entity properties/Attributes "Sys_xxxxxx" with DataReader Fields/Columns
            //Not neeed for ContentSummary
            //DatabaseCommon.TranslateSystemFieldsFromReaderToEntity(pContentSummaryObject, pDbDataReader);
        }
        #endregion Private Methods
    }
}
